<template>
  <el-container style="flex-direction: column; height: 100vh;">
      <!-- 顶部栏 -->
      <HeaderComponent :userInfo="this.userInfo" />

      <!-- 主内容区 -->
      <el-container style="flex-direction: row; height: 100vh;">
          <!-- 侧边栏 -->
          <SidebarComponent />

          <el-main style="overflow-y: auto;">
              <!-- 公告栏 -->
              <el-card class="announcement-box">
                  <div slot="header" class="clearfix"
                      style="display: flex; justify-content: space-between; align-items: center;">
                      <span>社区公告</span>
                      <el-button style="padding: 3px 0" type="text">查看更多</el-button>
                  </div>
                  <el-carousel :interval="5000" height="150px" arrow="always">
                      <el-carousel-item v-for="(item, index) in announcements" :key="index">
                          <div class="announcement-item">
                              <div class="title">{{ item.announcementTitle }}</div>
                              <div class="content">{{ item.announcementContent }}</div>
                              <div class="time">{{ item.updateTime.replace('T', ' ') }}</div>
                          </div>
                      </el-carousel-item>
                  </el-carousel>
              </el-card>

              <!-- 活动信息卡片和投诉建议 -->
              <el-row :gutter="20">
                  <el-col :span="18">
                      <el-card>
                          <div class="section-title">活动信息</div>
                          <el-row :gutter="20">
                              <el-col :span="6">
                                  <el-card shadow="hover">
                                      <div class="data-card">
                                          <div class="num">{{ activityCount.preparation }}</div>
                                          <div class="label">准备中</div>
                                      </div>
                                  </el-card>
                              </el-col>
                              <el-col :span="6">
                                  <el-card shadow="hover">
                                      <div class="data-card">
                                          <div class="num">{{ activityCount.signingUp }}</div>
                                          <div class="label">报名中</div>
                                      </div>
                                  </el-card>
                              </el-col>
                              <el-col :span="6">
                                  <el-card shadow="hover">
                                      <div class="data-card">
                                          <div class="num">{{ activityCount.inProgress }}</div>
                                          <div class="label">活动中</div>
                                      </div>
                                  </el-card>
                              </el-col>
                              <el-col :span="6">
                                  <el-card shadow="hover">
                                      <div class="data-card">
                                          <div class="num">{{ activityCount.ended }}</div>
                                          <div class="label">已结束</div>
                                      </div>
                                  </el-card>
                              </el-col>
                          </el-row>
                      </el-card>
                  </el-col>
                  <el-col :span="6">
                      <el-card shadow="hover" class="complaint-suggestions">
                          <div class="section-title">投诉建议</div>
                          <el-table :data="complaints" style="width: 100%" height="200">
                              <el-table-column prop="status" label="类型" width="80">
                                  <template #default="scope">
                                      <span v-if="scope.row.status === 1"> 投诉 </span>
                                      <span v-else-if="scope.row.status === 2"> 建议 </span>
                                  </template>
                              </el-table-column>
                              <el-table-column prop="content" label="内容" show-overflow-tooltip></el-table-column>
                              <el-table-column label="操作" width="80">
                                  <template #default="scope">
                                      <el-button type="text" @click="viewDetail(scope.row)">查看</el-button>
                                  </template>
                              </el-table-column>
                          </el-table>
                      </el-card>
                  </el-col>
              </el-row>

              <!-- ECharts 图表 -->
              <el-row :gutter="20" class="chart-section">
                  <el-col :span="24">
                      <el-card>
                          <div class="section-title">访客信息</div>
                          <el-row :gutter="20">
                              <el-col :span="12">
                                  <el-card>
                                      <!-- 增加饼图高度 -->
                                      <div ref="pieChart" style="width: 100%; height: 500px;"></div>
                                  </el-card>
                              </el-col>
                              <el-col :span="12">
                                  <el-card>
                                      <!-- 增加雷达图高度 -->
                                      <div ref="radarChart" style="width: 100%; height: 500px;"></div>
                                  </el-card>
                              </el-col>
                          </el-row>
                      </el-card>
                  </el-col>
              </el-row>
          </el-main>
      </el-container>
  </el-container>
</template>

<script>
import * as echarts from 'echarts';
import HeaderComponent from '@/components/property_components/PropertyHeader.vue';
import SidebarComponent from '@/components/property_components/PropertySidebar.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  components: {
      HeaderComponent,
      SidebarComponent
  },
  data() {
      return {
          // 活动数据
          activityData: [],
          activityCount: {
              preparation: '0',
              signingUp: '0',
              inProgress: '0',
              ended: '0',
          },
          // 投诉建议数据
          complaints: [],
          announcements: [],
          userInfo: {},
          applyData: [],
          todayApply: [],

          // 雷达图数据
          radarChartData: {
              applying: 0, // 申请中
              notArrived: 0, // 未到访
              arrived: 0, // 已到访
              rejected: 0, // 拒绝到访
              expired: 0 // 申请过期
          },
          // 饼图数据
          pieChartData: {
              applying: 0, // 申请中
              notArrived: 0, // 未到访
              arrived: 0, // 已到访
              rejected: 0, // 拒绝到访
              expired: 0 // 申请过期
          },


      };
  },
  mounted() {
      this.userInfo = parseJwt(localStorage.getItem('token')).payload;

      this.getRecentAnnouncement(); // 获取公告信息
      this.getComplaints();   // 获取投诉建议
      this.getActivity();     // 获取活动信息
      this.getApplyData();  // 获取申请数据
      this.getTodayApply(); // 获取当天申请
  },
  methods: {
      getRecentAnnouncement() {
          // 获取公告信息
          service.get('/api/user/announcement/getRecentAnnouncements')
             .then(result => {
                  //将result返回的数据赋值给result，即为controller返回的result
                  result = result.data;
                  if (result.code == 1) {
                      console.log('登录成功,公告信息:', result.data);
                      this.announcements = result.data.rows;
                  } else {
                      alert(result.msg);
                  }
              });
      },
      getActivity() {
          service.get('/api/user/activity/getActivityList')
             .then(result => {
                  result = result.data;
                  if (result.code == 1) {
                      console.log('登录成功,活动信息:', result.data);
                      this.activities = result.data;
                      this.activities.forEach(activity => {
                          switch (activity.status) {
                              case 1:
                                  this.activityCount.preparation++;
                                  break;
                              case 2:
                                  this.activityCount.signingUp++;
                                  break;
                              case 3:
                                  this.activityCount.inProgress++;
                                  break;
                              case 4:
                                  this.activityCount.ended++;
                                  break;
                          }
                      });
                  } else {
                      alert(result.msg);
                  }
              })
      },

      getComplaints() {
          service.get(`/api/admin/complaint/getComplaintAdvice`).then(result => {
              result = result.data
              if (result.code == 1) {
                  this.complaints = result.data;
                  console.log('投诉建议:', this.complaints);
              } else {
                  this.$message.error(result.msg);
              }
          }).catch(error => {
              this.$message.error('获取投诉建议失败');
              console.error(error);
          });
      },
      getTodayApply() {
          service.get('/api/admin/apply/getAllTodayApply')
             .then(result => {
                  //将result返回的数据赋值给result，即为controller返回的result
                  result = result.data;
                  if (result.code == 1) {
                      this.todayApply = result.data;
                      console.log('今日申请,this.todayApply:', this.todayApply)
                      this.updateChartData(); // 更新图表数据
                  } else {
                      alert(result.msg);
                  }
              }).catch(error => {
                  this.$message.error('获取今日申请失败');
                  console.error(error);
              });
      },
      getApplyData() {
          service.get('/api/admin/apply/getApply')
             .then(result => {
                  //将result返回的数据赋值给result，即为controller返回的result
                  result = result.data;
                  if (result.code == 1) {
                      this.applyData = result.data;
                      console.log('总申请,this.applyData:', this.applyData)
                  } else {
                      alert(result.msg);
                  }
              }).catch(error => {
                  this.$message.error('获取申请数据失败');
                  console.error(error);
              });
      },

      // 更新图表数据
      updateChartData() {
          this.pieChartData.applying = 0;
          this.pieChartData.notArrived = 0;
          this.pieChartData.arrived = 0;
          this.pieChartData.rejected = 0;
          this.pieChartData.expired = 0;

          this.radarChartData.applying = 0;
          this.radarChartData.notArrived = 0;
          this.radarChartData.arrived = 0;
          this.radarChartData.rejected = 0;
          this.radarChartData.expired = 0;

          this.todayApply.forEach(apply => {
              console.log('apply:', apply);
              if (apply.state === 1) {
                  this.pieChartData.applying++;
                  this.radarChartData.applying++;
              } else if (apply.state === 2) {
                  this.pieChartData.notArrived++;
                  this.radarChartData.notArrived++;
              } else if (apply.state === 3) {
                  this.pieChartData.arrived++;
                  this.radarChartData.arrived++;
              } else if (apply.state === 4) {
                  this.pieChartData.rejected++;
                  this.radarChartData.rejected++;
              } else if (apply.state === 5) {
                  this.pieChartData.expired++;
                  this.radarChartData.expired++;
              }
          });

          this.initPieChart();
          this.initRadarChart()
      },

      // 初始化饼状图
      initPieChart() {
          const chartDom = this.$refs.pieChart;
          if (!chartDom) return;

          // 销毁旧实例
          if (this.pieChart) {
              this.pieChart.dispose();
          }

          // 数据转换
          const pieData = [
              { name: '申请中', value: Number(this.pieChartData.applying) || 0 },
              { name: '未到访', value: Number(this.pieChartData.notArrived) || 0 },
              { name: '已到访', value: Number(this.pieChartData.arrived) || 0 },
              { name: '拒绝到访', value: Number(this.pieChartData.rejected) || 0 },
              { name: '申请过期', value: Number(this.pieChartData.expired) || 0 }
          ].filter(item => item.value > 0); // 过滤零值数据

          // 初始化图表
          this.pieChart = echarts.init(chartDom);
          const option = {
              title: {
                  text: '访客状态分布',
                  left: 'center',
                  top: 20,
                  textStyle: {
                      fontSize: 16,
                      color: '#333'
                  }
              },
              tooltip: {
                  trigger: 'item',
                  formatter: ({ name, value, percent }) =>
                      `${name}<br/>数量: ${value} (${percent}%)`
              },
              legend: {
                  bottom: 20,
                  orient: 'horizontal',
                  data: pieData.map(d => d.name),
                  textStyle: {
                      color: '#666'
                  }
              },
              color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'],
              series: [{
                  type: 'pie',
                  radius: ['40%', '70%'],
                  center: ['50%', '45%'],
                  avoidLabelOverlap: true,
                  label: {
                      show: true,
                      formatter: ({ name, percent }) =>
                          `${name}\n${percent}%`,
                      fontSize: 12,
                      lineHeight: 16
                  },
                  labelLine: {
                      show: true,
                      length: 8,
                      length2: 12
                  },
                  data: pieData,
                  emphasis: {
                      scale: true,
                      scaleSize: 5,
                      itemStyle: {
                          shadowBlur: 10,
                          shadowColor: 'rgba(0, 0, 0, 0.3)'
                      }
                  }
              }]
          };

          this.pieChart.setOption(option);
          this.addChartResizeListener(this.pieChart);
      },

      // 初始化雷达图
      initRadarChart() {
          const chartDom = this.$refs.radarChart;
          if (!chartDom) return;

          // 销毁旧实例
          if (this.radarChart) {
              this.radarChart.dispose();
          }

          const radarData = [
              { name: '申请中', value: this.radarChartData.applying },
              { name: '未到访', value: this.radarChartData.notArrived },
              { name: '已到访', value: this.radarChartData.arrived },
              { name: '拒绝到访', value: this.radarChartData.rejected },
              { name: '申请过期', value: this.radarChartData.expired }
          ];

          const maxValue = Math.max(...radarData.map(item => item.value));

          // 初始化图表
          this.radarChart = echarts.init(chartDom);
          const option = {
              title: {
                  text: '访客状态雷达图',
                  left: 'center',
                  top: 20,
                  textStyle: {
                      fontSize: 16,
                      color: '#333'
                  }
              },
              tooltip: {
                  trigger: 'item'
              },
              legend: {
                  bottom: 20,
                  data: ['访客状态'],
                  textStyle: {
                      color: '#666'
                  }
              },
              radar: {
                  indicator: radarData.map(item => ({ name: item.name, max: maxValue })),
                  shape: 'circle',
                  center: ['50%', '50%'],
                  radius: '70%'
              },
              series: [{
                  name: '访客状态',
                  type: 'radar',
                  data: [
                      {
                          value: radarData.map(item => item.value),
                          name: '访客状态'
                      }
                  ],
                  areaStyle: {
                      opacity: 0.2
                  },
                  lineStyle: {
                      width: 2
                  },
                  itemStyle: {
                      color: '#5470C6'
                  }
              }]
          };

          this.radarChart.setOption(option);
          this.addChartResizeListener(this.radarChart);
      },

      // 添加图表响应式监听
      addChartResizeListener(chartInstance) {
          const resizeHandler = () => chartInstance.resize();
          window.addEventListener('resize', resizeHandler);

          // 组件销毁时移除监听
          this.$once('hook:beforeDestroy', () => {
              window.removeEventListener('resize', resizeHandler);
              chartInstance.dispose();
          });
      },
      // 查看投诉建议详情
      viewDetail(row) {
          this.$alert(row.content, '详情', {
              confirmButtonText: '关闭'
          });
      }
  }
};
</script>

<style scoped>
.announcement-box {
  margin-bottom: 20px;
  height: 200px;
}

.announcement-item {
  padding: 10px;
  text-align: center;
}

.announcement-item .title {
  font-weight: bold;
}

.announcement-item .content {
  color: #666;
  margin: 5px 0;
}

.announcement-item .time {
  color: #999;
  font-size: 12px;
}

.data-card {
  text-align: center;
  padding: 20px 0;
}

.data-card .num {
  font-size: 24px;
  font-weight: bold;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.complaint-suggestions {
  height: 100%;
}

.chart-section {
  margin-top: 30px;
  /* 图表与活动信息的间距 */
}
</style>    